import React, {useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {SYS_ENUMS} from "@/utils/constants";
import {SaleAfterManager} from "@/services/api-functions";
import {isSuccess} from "@/utils/utils";
import {Form, message, Modal, Radio, Table} from "antd";
import {ModalForm, ProFormSelect, ProFormTextArea} from "@ant-design/pro-form";


export const afterSaleAudit = async (fields: any, select: any) => {
  if (!select) return false;
  try {
    if (isSuccess((await SaleAfterManager.approve({
      businessId: select.id,
      auditOperate: fields.auditOperate,
      remark: fields.remark,
      flowType: 'SALE_AFTER_REFUND',
    }))?.code)) {
      message.success(fields.auditOperate === SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value ? '审核通过' : '审核拒绝');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

const SalesAfterList: React.FC<any> = (props) => {

  const countInfoInit = {
    all: undefined,
    REFUNDING: undefined,
    REFUND_SUCCESS: undefined,
    REFUND_FAIL: undefined,
  }
  const [auditFormRef] = Form.useForm()
  const [orderStatus, setOrderStatus] = useState<'all' | 'pending' | 'success' | 'cancel'>('all');
  const [countInfo, setCountInfo] = useState<{ all: number | undefined, REFUNDING: number | undefined, REFUND_SUCCESS: number | undefined, REFUND_FAIL: number | undefined, doing?: number | undefined }>({
    all: undefined,
    REFUNDING: undefined,
    REFUND_SUCCESS: undefined,
    REFUND_FAIL: undefined,
  });
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<any>();
  const [preview, setPreview] = useState<boolean>(false);
  const [auditVisible, handleAuditVisible] = useState<boolean>(false);
  const BASE_COLUMNS: ProColumns[] = [
    {
      title: '用户名',
      dataIndex: 'nickName',
      ellipsis: true,
      hideInTable: true,
      width: 120,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      width: 150,
      hideInTable: true,
    },
    {
      title: '订单类型',
      dataIndex: 'orderType',
      valueEnum: SYS_ENUMS.ORDER_TYPE,
      ellipsis: true,
      hideInTable: true,
      width: 120,
    },
    {
      title: '退款时间',
      dataIndex: 'gmtCreateTimeRange',
      valueType: 'dateTimeRange',
      width: 170,
      hideInTable: true,
    },
    {
      title: '订单号',
      dataIndex: 'orderId',
      hideInTable: true,
      fixed: 'left'
    },
    {
      title: '退款信息',
      dataIndex: 'moneyInfo',
      ellipsis: true,
      width: 250,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>退款编号：{entity?.id ?? '-'}</p>
        <p>申请时间：{entity?.gmtCreate ?? '-'}</p>
        <p>退款时间：{entity?.refundTime ?? '-'}</p>
      </div>
    },
    {
      title: '买家信息',
      dataIndex: 'buyerInfo',
      ellipsis: true,
      width: 220,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>用户名：{entity?.buyerDto?.nickName ?? '-'}</p>
        <p>联系电话：{entity?.buyerDto?.phone ?? '-'}</p>
        {
          !!entity?.buyerDto?.izMembers && <p>会员等级：{entity?.buyerDto?.certification ?? '-'}</p>
        }
      </div>
    },
    {
      title: '卖家信息',
      dataIndex: 'buyerInfo',
      ellipsis: true,
      width: 250,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>标题名称：{entity?.title ?? '-'}</p>
        <p>设计师：{entity?.sellerDto?.nickName ?? '-'}</p>
      </div>
    },
    {
      title: '订单信息',
      dataIndex: 'orderInfo',
      ellipsis: true,
      width: 250,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>订单编号：{entity?.orderId ?? '-'}</p>
        <p>订单状态：<span style={{color:SYS_ENUMS.ORDER_STATUS[entity?.orderStatus]?.color ?? 'gray'}}>{SYS_ENUMS.ORDER_STATUS[entity?.orderStatus]?.text ?? '-'}</span></p>
        <p>订单类型：{SYS_ENUMS.ORDER_TYPE[entity?.orderType].text ?? '-'}</p>
      </div>
    },
    {
      title: '金额信息',
      dataIndex: 'moneyInfo',
      ellipsis: true,
      width: 170,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>付款金额：<span style={{color:'red'}}>{entity?.realPayment ?? '-'}</span></p>
        <p>退款金额：<span style={{color:'red'}}>{entity?.exInfo?.amount ?? '-'}</span></p>
        <p>退款去向：{SYS_ENUMS.PAYMENT_TYPE[entity?.paymentChannel].text ?? '-'}</p>
      </div>
    },
    {
      title: '退款详情',
      dataIndex: 'payInfo',
      ellipsis: true,
      width: 250,
      hideInSearch: true,
      render: (dom, entity) => <div>
        <p>退款原因：{entity?.exInfo?.reason ?? '-'}</p>
        <p>详细描述：{entity?.exInfo?.describe ?? '-'}</p>
        <p>截图凭证：{entity?.exInfo?.ossPojoList ? <a key="edit" onClick={() => {
          setCurrentRow(entity)
          setPreview(true)
        }}>查看</a> : '-'}</p>
      </div>
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        record.saleStatus === 'REFUNDING'
          ? <a key="edit" onClick={() => {
            setCurrentRow(record)
            auditFormRef?.resetFields()
            handleAuditVisible(true)
          }}>处理申请</a>
          : <a key="edit" style={{color: "gray"}}>处理申请</a>
      ],
    },
  ]

  return (
    <PageContainer>
      <ProTable<any, any>
        headerTitle={<Radio.Group value={orderStatus} onChange={(e) => {
          setOrderStatus(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='all'>全部 {countInfo?.all ?? ''}</Radio.Button>
          <Radio.Button value='REFUNDING'>待处理 {countInfo?.REFUNDING ?? ''}</Radio.Button>
          <Radio.Button value='REFUND_SUCCESS'>退款成功 {countInfo?.REFUND_SUCCESS ?? ''}</Radio.Button>
          <Radio.Button value='REFUND_FAIL'>退款失败 {countInfo?.REFUND_FAIL ?? ''}</Radio.Button>
        </Radio.Group>}
        actionRef={actionRef}
        rowKey="key"
        search={{labelWidth: 120,}}
        request={async (params) => {

          const query = {...params}
          if (orderStatus !== 'all') {
            query.saleStatus = orderStatus
          }

          if (params.gmtCreateTimeRange) {
            query.startTime = params.gmtCreateTimeRange[0]
            query.endTime = params.gmtCreateTimeRange[1]
            delete query.gmtCreateTimeRange
          }

          const {data: {data, total}, code}: any = await SaleAfterManager.pageQuery(query)

          setCountInfo({...countInfoInit, [orderStatus]: total})

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={BASE_COLUMNS}
        scroll={{x: 1300}}
      />
      <ModalForm
        title={`审核【${currentRow?.title}】`}
        width="750px"
        form={auditFormRef}
        visible={auditVisible}
        onVisibleChange={v => {
          handleAuditVisible(v)
          if (!v) {
            auditFormRef?.resetFields()
          }
        }}
        onFinish={async (value) => {
          // @ts-ignore
          if (await afterSaleAudit(value as any, currentRow)) {
            handleAuditVisible(false);
            auditFormRef?.resetFields()
            setCurrentRow(undefined)
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormSelect label='审核结果' required rules={[{required: true, message: '请填选择审核结果',},]} name='auditOperate'
                       initialValue={SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value} options={[
          {label: '同意退款', value: SYS_ENUMS.RESOURCE_AUDIT_STATE.PASS.value},
          {label: '拒绝退款', value: SYS_ENUMS.RESOURCE_AUDIT_STATE.REFUSE.value},
        ]}/>
        <ProFormTextArea label='备注' name="remark"/>
      </ModalForm>
      <Modal width={750} title='查看截图凭证' visible={preview && currentRow} onCancel={() => {
        setPreview(false);
        setCurrentRow(undefined)
      }}>
        <Table
          dataSource={currentRow?.exInfo?.ossPojoList ?? []}
          columns={[
            {
              title: '序号',
              dataIndex: 'index',
              ellipsis: true,
              width: 100,
              render: (_, record, index) => index + 1,
            },
            {
              title: '名称',
              dataIndex: 'name',
              ellipsis: true,
            },
            {
              title: '操作',
              width: 170,
              dataIndex: 'option',
              render: (_, record) => <a key={record?.key} href={record?.url} target='_blank' rel="noreferrer">下载</a>,
            },
          ]}/>
      </Modal>
    </PageContainer>
  );
};

export default SalesAfterList;
